/**
 * Copyright (c) 2016-2020, Michael Yang 杨福海 (fuhai999@gmail.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.rock.app.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.eova.common.utils.xx;
import com.eova.common.utils.io.FileUtil;
import com.eova.config.EovaConst;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;
import com.rock.app.base.OpenControllerBase;

import cn.hutool.core.date.DateUtil;


/**
 * 上传图片，暂未实现
 * @author jadison
 *
 */
public class AttachmentController extends OpenControllerBase {

    public void upload() {

        UploadFile uploadFile = getFile();
        if (uploadFile == null) {
            renderJson(Ret.fail().set("message", "请选择要上传的文件"));
            return;
        }

        File file = uploadFile.getFile();
        
		//判断用户身份
		 if (getLoginedUserApi()==null) {
			 file.delete();
		 renderFailJson(4000,"用户未激活，禁止上传");
		 return; 
		 }
		
//		 附件存储目录
		 String baseDir = File.separator + "attachment" + File.separator + DateUtil.format(new Date(), "yyyyMMdd");
		 //2代表所有文件
		 FileStatus fs = saveFile(baseDir, null,2);
		 if(!fs.isSuccess()) {
			 this.renderFailJson(4000,fs.getMsg());
			 return;
		 }

        Map<String,Object> data = new HashMap<String, Object>();
        data.put("success", true);
        data.put("src", fs.getFileName());
        data.put("alisrc1", "ALIOSSURL");

        renderOkDataJson(data);
    }

	/**
	 * 通用上传文件
	 * @param fileDir 指定基本路径
	 * @param name 收到的文件名，部分控件不支持送文件名则不用送
	 * @param type 类型；1-图片，2-文件
	 * @return
	 */
	public FileStatus saveFile(String fileDir,String name, int type) {
		if(fileDir == null){//未指定路径，则从req参数提取
			fileDir = getPara("filedir");
			if (xx.isEmpty(fileDir)) {
				fileDir = xx.getConfig("eova_upload_temp");
			}
		}
		
		String fileName = "";
		boolean isDelete = true;
		UploadFile file = null;
		String srcName = null;
		String domain = null;
		try {
			if (name != null) {
				// 按参数名获取上传文件
				file = getFile(name, fileDir);
			} else {
				// 获取第一个上传文件
				List<UploadFile> files = getFiles(fileDir);
				if (xx.isEmpty(files)) {
					return new FileStatus(false,"请选择一个文件！");
				}
				file = files.get(0);
			}
			
			
			// 上传到/upload 目录（也有可能冲突）
			if (xx.isEmpty(file)) {
				return new FileStatus(false,"请选择一个文件！");
			}
			
			int limit = 5120;
			
			if(type == 1){
				limit = EovaConst.UPLOAD_IMG_SIZE;
				domain = xx.getConfig("domain_img");
			}else if(type == 2){
				limit = EovaConst.UPLOAD_FILE_SIZE;
				domain = xx.getConfig("domain_file");
			}
			
			// 大小限制
			if (FileUtil.checkFileSize(file.getFile(), limit)) {
					String msg = "图片大小不能超过"+limit/(1024)+"M";
					return new FileStatus(false,msg);
			}
			// 文件后缀
			if(type == 1)
				if (!FileUtil.checkFileType(file.getFile().getPath(), true)) {
					return new FileStatus(false,"请勿上传非法类型文件");
				}
			else if(type == 2)
				if (!FileUtil.checkFileType(file.getFile().getPath(), false)) {
					return new FileStatus(false,"请勿上传非法类型文件");
				}

			// 获取文件名(文件原名)
			srcName = file.getFileName();
			// 获取文件后缀
			String suffix = FileUtil.getFileType(srcName);
			// 创建新的随机文件名（也有可能冲突）
			fileName = System.currentTimeMillis() + suffix;

			// 新文件 Path，增加attachment目录，没有时先创建
			String dir = file.getUploadPath() + fileDir;
			File df = new File(dir);
			if(!df.exists()) {
				df.mkdirs();
			}
			
			String path = dir + File.separator + fileName;

			FileUtil.rename(file.getFile().getPath(), path);
			System.out.println(file.getFile().getPath());
			System.out.println(path);
			
			fileName = fileDir.replace("\\", "/") +"/"+ fileName;
			
			isDelete = false;
			
		} catch (Exception e) {
			e.printStackTrace();
			return new FileStatus(false,"系统异常：文件上传失败,请稍后再试");
		} finally {
			if (isDelete) {
				// 强制删除已上传的文件(如果还存在)
				FileUtil.delete(file.getFile());
				LogKit.info("图片回收");
			}
		}
		
		return new FileStatus(true,"上传成功",srcName,fileName,xx.getConfig("static_root"),domain);
	}
	

	public class FileStatus {
	    boolean success = false;
	    String msg = null;
	    String srcName = null;// 文件源名称
	    String fileName = null; // 文件相对路径： /upload/aaaa.jpg 如果经过云存储则此字段数据修改成：http：//xx/aaaaas
	    String baseDir = null; //文件base路径，系统中配置 的 /opt/apache-tomcat-7.0.69/webapps/files
	    //添加的访问域名如：http://127.0.0.1
	    String domain = null;
	    boolean transStatus = false;
	    
	    public FileStatus(boolean success,String msg) {
	    	this.success = success;
	    	this.msg = msg;
	    }
	    
	    public FileStatus(boolean success,String msg,String srcName,String fileName,String baseDir,String domain) {
	        this.success = success;
	        this.msg = msg;
	        
	        this.srcName = srcName;
	        this.fileName = fileName;
	        this.baseDir = baseDir;
	        this.domain = domain;
	    }

		public boolean isSuccess() {
			return success;
		}

		public void setSuccess(boolean success) {
			this.success = success;
		}

		public String getMsg() {
			return msg;
		}

		public void setMsg(String msg) {
			this.msg = msg;
		}

		public String getSrcName() {
			return srcName;
		}

		public void setSrcName(String srcName) {
			this.srcName = srcName;
		}

		public String getFileName() {
			return fileName;
		}

		public void setFileName(String fileName) {
			this.fileName = fileName;
		}

		public String getBaseDir() {
			return baseDir;
		}

		public void setBaseDir(String baseDir) {
			this.baseDir = baseDir;
		}

		public String getDomain() {
			return domain;
		}

		public void setDomain(String domain) {
			this.domain = domain;
		}

		public boolean isTransStatus() {
			return transStatus;
		}

		public void setTransStatus(boolean transStatus) {
			this.transStatus = transStatus;
		}
	     
	    
	}
}
